package com.lej.my.collect

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lej.core.base.BaseModel
import com.lej.core.base.BaseViewModel
import com.lej.dataservice.club.bean.main.my.MyCollectInfo
import com.lej.dataservice.club.http.base.getBody
import com.lej.dataservice.club.http.checkData
import com.lej.my.http.myApiService
import kotlinx.coroutines.launch

/**
 *  author: cjq
 *  date  : 2022/6/9 0009
 *  desc  :
 */
const val LoadMoreSuccess = 1
const val LoadMoreError = 2
const val LoadMoreComplete = 3
const val LoadEmpty = 4
const val LoadError = 5
const val LoadLoading = 6
const val LoadSuccess = 7

class MyCollectViewModel : BaseViewModel<BaseModel>() {

    private val pageSize: Int = 30
    var page: Int = 0
    var infoList: ArrayList<MyCollectInfo> = ArrayList()

    var loadingState: MutableLiveData<Int> = MutableLiveData(0)

    fun getCollectData(
        isLoadMore: Boolean,
        loadResult: (List<MyCollectInfo>?, List<MyCollectInfo>?) -> Unit
    ) {
        if (!isLoadMore) page = 1
        viewModelScope.launch {
            kotlin.runCatching {
                if (!isLoadMore) loadingState.value = LoadLoading
                val list =
                    myApiService.getMyCollect(getBody("page" to page, "page_size" to pageSize))
                        .checkData().list
                if (list?.isNullOrEmpty() == true) {
                    loadingState.value = if (isLoadMore) LoadMoreComplete else LoadEmpty
                } else {
                    if (isLoadMore) {
                        infoList.addAll(list)
                        loadResult.invoke(null, list)
                    } else {
                        infoList.clear()
                        infoList.addAll(list)
                        loadResult.invoke(list, null)
                    }
                    if (list.size < pageSize) {
                        loadingState.value = LoadMoreComplete
                        if (!isLoadMore) loadingState.value = LoadSuccess
                    } else {
                        loadingState.value = if (isLoadMore) LoadMoreSuccess else LoadSuccess
                    }
                    page++
                }
            }.onFailure {
                loadingState.value = if (isLoadMore) LoadMoreError else LoadError
            }
        }
    }
}